package com.heima.article.listener;

import com.heima.article.service.IApArticleService;
import com.heima.common.constants.rabbit.RabbitArticlePublishConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.Payload;

import java.io.IOException;

@Configuration
@Slf4j
public class RabbitArticlePublishListener {

    @Autowired
    private IApArticleService apArticleService;

    @RabbitListener(queuesToDeclare = @Queue(value = RabbitArticlePublishConstants.ARTICLE_PUBLISH_DEAD_QUEUE))
    public void listenerArticlePublishQueue(@Payload String newsId, Message message, Channel channel){
        log.info("文章定时发布消息成功投递到消费者，WmNews id: {}", newsId);
        try {
            apArticleService.publishArticle(Integer.parseInt(newsId));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("文章定时发布处理完成，已返回 ACK 确认");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文章定时发布处理失败，失败原因: {}", e.getMessage());
        }
    }

}
